window.onload=function(){
	/*
	date.getFullYear(); //获取完整的年份(4位)
	date.getMonth(); //获取当前月份(0-11,0代表1月)
	date.getDate(); //获取当前日(1-31)
	date.getDay(); //获取当前星期X(0-6,0代表星期天)
	*/
	if(rwLS("r","str_jsonData")){//如果本地已经储存数据，则直接读取展示.
		console.log("have data");
		user_data = JSON.parse(rwLS("r","str_jsonData"));
		result = user_data['result'];
			
			lessonList = result['lessonList'];
			scheduleList = result['scheduleList'];
			scheduleGroupList = result['scheduleGroupList'];

			//id和课程名称
			lessonName={"test":"test"}
			for(lesson0 in lessonList){
				lessonName[lessonList[lesson0]['id']]=lessonList[lesson0]['courseName'];
			}
			//id和对应颜色
			lessonColor={"test":"test"};
			colorlist=["#1890FF","#c22dc7","#FF1493","#7B68EE","#00d5d5","#00bd5b","#2E8B57","#aa557f","#d6b300","#ffc745","#00aa00","#D90000","#7B68EE","#00d5d5","#00bd5b","#2E8B57","#aa557f","#d6b300","#ffc745"];
			for(lesson0 in lessonList){
				lessonColor[ lessonList[lesson0]['id'] ]=colorlist[lesson0];
			}
			num_wd=jiaoxuezhou();
			$(count_week).html('第<a style="color:red;">'+num_wd+'</a>周');
			getSchedule(jiaoxuezhou());
			

		
	}else{//否则向服务器请求数据
		console.log("写入数据");
		window.JSBridge.getUserdata();
			//如果已经登陆
			//js调用Java获取数据
			//java调用js写入数据，储存到localstorage
	}

}
function java_savedata(data){
	try{
		  var xhr = new XMLHttpRequest();
		  xhr.open("get", "https://api.iou.ink/HFUTcourse/"+data, true);
		  xhr.onreadystatechange = function() {
		    if (xhr.readyState == 4 && xhr.status == 200) {
		      //console.log(xhr.responseText);
		      var user_data0= eval('(' + xhr.responseText.replace(/\None/g,"'None'").replace(/\True/g,"'True'").replace(/\False/g,"'False'") + ')');
              var user_data = eval('(' + user_data0 + ')');
              var str_jsonData = JSON.stringify(user_data);
			  rwLS("w","str_jsonData",str_jsonData);
			  swal("请求课表信息成功,如果未自动刷新请退出重进","","success");
			  setTimeout("window.location.reload();", 1500)
		    }
		  };
		  xhr.send(null);
		  swal("正在请求课表信息");
	}
	catch(e)//IE
	{alert(e)}
}

function getSchedule(weekindex){
	//根据教学周生成课表
	userdata=[]
	for(l_obj1 in scheduleList){
		if(scheduleList[l_obj1]["weekIndex"]==weekindex){
			//for(var day= 0;day<7;day++){if(scheduleList[l_obj1]["weekday"] ==day){}}
			var rtjson=[{
				"lessonID":scheduleList[l_obj1]["lessonId"],
				"courseName":lessonName[scheduleList[l_obj1]["lessonId"]],
				"teacher":scheduleList[l_obj1]["personName"],
				"date":scheduleList[l_obj1]["date"],
				"starttime":scheduleList[l_obj1]["startTime"],
				"weekday":scheduleList[l_obj1]["weekday"],
				"position":scheduleList[l_obj1]["room"]["nameZh"]
				}];
			userdata.push(rtjson);
		}
	}
	settable(userdata);
}
   
function jiaoxuezhou(){
	var date = new Date();
	switch((date.getMonth()+1)) {
			case 5:
				if([3,4,5,6,7,8,9].includes(date.getDate())){
					return 9
				}else if([10,11,12,13,14,15,16].includes(date.getDate())){
					return 10
				}else if([17,18,19,20,21,22,23].includes(date.getDate())){
					return 11
				}else if([24,25,26,27,28,29,30].includes(date.getDate())){
					return 12
				}else if([31].includes(date.getDate())){
					return 13
				}
				break;
			case 6:
				if([1,2,3,4,5,6].includes(date.getDate())){
					return 13
				}else if([7,8,9,10,11,12,13].includes(date.getDate())){
					return 14
				}else if([14,15,16,17,18,19,20].includes(date.getDate())){
					return 15
				}else if([21,22,23,24,25,26,27].includes(date.getDate())){
					return 16
				}else if([28,29,30].includes(date.getDate())){
					return 17
				}
				break;
			case 7:
				if([1,2,3,4].includes(date.getDate())){
					return 18
				}else if([5,6,7,8,9,10,11].includes(date.getDate())){
					return 19
				}else if([12,13,14,15,16,17,18].includes(date.getDate())){
					return 20
				}else if([19,20,21,22,23,24,25].includes(date.getDate())){
					//已经是暑假了
					return 21
				}else if([26,27,28,29,30,61].includes(date.getDate())){
					return 22
				}
				break;
			default:
				return "none"
	} 
}

showdetail=function(id){
	detaildata = user_data;
	for(dta in detaildata["result"]["lessonList"]){
		if( detaildata["result"]["lessonList"][dta]["id"] == id ){
			$(courseName).html(detaildata["result"]["lessonList"][dta]["courseName"]);
			$(code).html(detaildata["result"]["lessonList"][dta]["code"]);
			$(classname).html(detaildata["result"]["lessonList"][dta]["name"]);
			$(courseTypeName).html(detaildata["result"]["lessonList"][dta]["courseTypeName"]);
			$(teacherAssignmentList).html("");
			for(dta1 in detaildata["result"]["lessonList"][dta]["teacherAssignmentList"]){
				$(teacherAssignmentList).append('<div>任课教师:'+detaildata["result"]["lessonList"][dta]["teacherAssignmentList"][dta1]["name"]+'</div><div>年龄:'+detaildata["result"]["lessonList"][dta]["teacherAssignmentList"][dta1]["age"]+'<br>职位:'+detaildata["result"]["lessonList"][dta]["teacherAssignmentList"][dta1]["titleName"]+'<br>教师学号:'+detaildata["result"]["lessonList"][dta]["teacherAssignmentList"][dta1]["code"])
				//$(teacherAssignmentList).html();
			}
		}
	}
	for(dta1 in detaildata["result"]["scheduleGroupList"]){
		if( detaildata["result"]["scheduleGroupList"][dta1]["lessonId"] == id ){
			$(class_time).html(detaildata["result"]["scheduleGroupList"][dta1]["actualPeriods"]);
			$(student_num).html(detaildata["result"]["scheduleGroupList"][dta1]["stdCount"]);
		}
	}
	document.getElementById('detail').style.display='block';
}

function settable(userdata){
	var date = new Date();
	document.getElementById("date").innerText="今天是"+date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日\n"+"本学期第"+jiaoxuezhou()+"个教学周";
		var table_tr =$("#course-table tr");
		for(var i=0;i<table_tr.length;i++){
			if(i == table_tr.length){
				break;
			}
			console.log("第"+(i+1)+"行-------------------------");
			var table_td=$(table_tr[i]).find("td");
			for(var j=0;j<table_td.length;j++){
				if(i==0){
					//第一行赋值
					/*
					date.getFullYear(); //获取完整的年份(4位)
					date.getMonth(); //获取当前月份(0-11,0代表1月)
					date.getDate(); //获取当前日(1-31)
					date.getDay(); //获取当前星期X(0-6,0代表星期天)
					*/
					var weekdays=["周一","周二","周三","周四","周五","周六","周日"]
					var thismonth = getDay( (j-date.getDay())+ (num_wd-jiaoxuezhou())*7 ,"month");
					var thisday = getDay( (j-date.getDay())+ (num_wd-jiaoxuezhou())*7 +1,"day");
					str001 =(date.getMonth()+1)+"月";
					if(date.getDay() !=0){
						str001 =thismonth+"-"+thisday;
					}else{
						str001 =thismonth+"-"+thisday;
					}
					table_td[j].innerHTML=(weekdays[j]+'<br>'+str001);
					table_td[j].style.color="white";
					//如果是今天，字体改为红色
					if(num_wd==jiaoxuezhou()){
						table_td[date.getDay()-1].style.color="#ff0000";
						table_td[date.getDay()-1].style.fontWeight="bolder";
					}else{
						table_td[date.getDay()-1].style.color="white";
						table_td[date.getDay()-1].style.fontWeight="700";
					}
				}else{

						//table_td[j].innerHTML=("第"+(i+1)+"行"+(j+1)+"列");
						table_td[j].innerHTML=("  ");
						table_td[j].style.height="15vh";
						for(var s=0;s<userdata.length;s++){
							if(userdata[s][0]["weekday"]==j+1){//判断列
								//判断行
								switch(userdata[s][0]["starttime"]){
									case 810:
										if(i==1){
											table_td[j].innerHTML='<div onclick="showdetail('+userdata[s][0]["lessonID"]+')" class="td_style" style="background-color:'+lessonColor[userdata[s][0]["lessonID"]]+';">'+userdata[s][0]["courseName"].slice(0,15)+'<br><br><span style="">'+userdata[s][0]["position"]+'</span></div>';
										}
										break;
									case 1020:
										if(i==2){
											table_td[j].innerHTML='<div onclick="showdetail('+userdata[s][0]["lessonID"]+')" class="td_style" style="background-color:'+lessonColor[userdata[s][0]["lessonID"]]+';">'+userdata[s][0]["courseName"].slice(0,15)+'<br><br><span style="">'+userdata[s][0]["position"]+'</span></div>';
										}
										break;
									case 1400:
										if(i==3){
											table_td[j].innerHTML='<div onclick="showdetail('+userdata[s][0]["lessonID"]+')" class="td_style" style="background-color:'+lessonColor[userdata[s][0]["lessonID"]]+';">'+userdata[s][0]["courseName"].slice(0,15)+'<br><br><span style="">'+userdata[s][0]["position"]+'</span></div>';
										}
										break;
									case 1600:
										if(i==4){
											table_td[j].innerHTML='<div onclick="showdetail('+userdata[s][0]["lessonID"]+')" class="td_style" style="background-color:'+lessonColor[userdata[s][0]["lessonID"]]+';">'+userdata[s][0]["courseName"].slice(0,15)+'<br><br><span style="">'+userdata[s][0]["position"]+'</span></div>';
										}
										break;
									case 1900:
										if(i==5){
											table_td[j].innerHTML='<div onclick="showdetail('+userdata[s][0]["lessonID"]+')" class="td_style" style="background-color:'+lessonColor[userdata[s][0]["lessonID"]]+';">'+userdata[s][0]["courseName"].slice(0,15)+'<br><br><span style="">'+userdata[s][0]["position"]+'</span></div>';
										}
										break;
									default:
										return "none"
								}
							}
						}

					
				}
			}
		}
}

function rwLS(str,key,value){
	if(str == 'r'){
		return localStorage.getItem(key);
	}else if(str == 'w'){
		localStorage.setItem(key,value);
		return 1;
	}else if(str == 'rm'){
		localStorage.removeItem(key);
		return 2;
	}
}

function changeSD(flag0){
	if(num_wd<21 && 0<num_wd){
		if(flag0=="-1"){
		    if(1<num_wd){
		        num_wd -=1;
		        $(count_week).html('第<a style="color:red;">'+num_wd+'</a>周');
		        getSchedule(num_wd);
		    }else{
		        window.JSBridge.showSometh('-')
		    }
		}else if(flag0=="+1"){
		    if(num_wd<20){
		        num_wd +=1;
		        $(count_week).html('第<a style="color:red;">'+num_wd+'</a>周');
		        getSchedule(num_wd);
		    }else{
		        window.JSBridge.showSometh('+')
		    }

		}
	}
}
function getDay(days,flag2){
        var today = new Date();
        var targetday_milliseconds=today.getTime() + 1000*60*60*24*days;
        today.setTime(targetday_milliseconds);
        var tYear = today.getFullYear();
        var tMonth = today.getMonth();
        var tDate = today.getDate();
        tMonth = this.doHandleMonth(tMonth + 1);
        tDate = this.doHandleMonth(tDate);
		if(flag2=="day"){
			return tDate;
		}else if (flag2=="month"){
			return tMonth
		}else{
			return tYear+"-"+tMonth+"-"+tDate;
		}
        
      }
function doHandleMonth(month){
              var m = month;
              if(month.toString().length == 1){
                  m = "0" + month;
              }
              return m;
      }
